package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Page;
import com.example.springboot.common.Result;
import com.example.springboot.dto.CreativeDTO;
import com.example.springboot.dto.CreativeHomeDTO;
import com.example.springboot.entity.Creative;
import com.example.springboot.entity.User;
import com.example.springboot.dto.UserDTO;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.CreativeMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.ICCollectionService;
import com.example.springboot.service.ICCommentService;
import com.example.springboot.service.ICreativeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.TimeUtil;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CreativeServiceImpl extends ServiceImpl<CreativeMapper, Creative> implements ICreativeService {

    @Resource
    private CreativeMapper creativeMapper;
    @Resource
    private ICreativeService creativeService;
    @Resource
    private ICCommentService commentService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ICCollectionService collectionService;

    @Override   //创意社区
    public HashMap<String, List<CreativeDTO>> findAll() {
        List<CreativeDTO> result = new ArrayList<>();
        HashMap<String,List<CreativeDTO>> hashMap = new HashMap<>();
        List<Creative> list;
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("statement","已发布");
        list = creativeMapper.selectList(queryWrapper);
        List<Creative> list1 = creativeMapper.countComments();
        List<Creative> list2 = creativeMapper.countCollections();
        for (Creative creative : list) {
            CreativeDTO creativeDTO = new CreativeDTO();
            UserDTO userDTO = new UserDTO();
            User user = userMapper.selectById(creative.getUserId());
            creativeDTO.setId(creative.getId());
            //
            userDTO.setId(user.getId());
            userDTO.setNickname(user.getNickname());
            userDTO.setProfilepic(user.getProfilepic());
            creativeDTO.setUserDTO(userDTO);
            //
            creativeDTO.setName(creative.getName());
            creativeDTO.setType(creative.getType());
            creativeDTO.setView(creative.getView());
            creativeDTO.setCreateTime(creative.getCreateTime().toLocalDate());
            creativeDTO.setRelativeTime(TimeUtil.createRelative(creative.getCreateTime()));
            creativeDTO.setFeature(Arrays.asList(creative.getFeature().split(" ")));
            if (creative.getDetail().length() <= 50)
                creativeDTO.setDetail(creative.getDetail());
            else
                creativeDTO.setDetail(creative.getDetail().substring(0,50));
            if (!creative.getPicture().equals("{}")){
                creativeDTO.setCommunityPic(new JSONObject(creative.getPicture()).get("response").toString());
            }
            else {
                if (!creative.getSketch().equals("{}")){
                    creativeDTO.setCommunityPic(new JSONObject(creative.getSketch()).get("response").toString());
                }
            }
            for (Creative creative1 : list1) {
                if (creative.getId().equals(creative1.getId()))
                    creativeDTO.setComments(creative1.getComments());
            }
            for (Creative creative2 : list2) {
                if (creative.getId().equals(creative2.getId()))
                    creativeDTO.setCollections(creative2.getCollections());
            }
            result.add(creativeDTO);
        }
        List<CreativeDTO> timeList = new ArrayList<>(result);
        List<CreativeDTO> viewList = new ArrayList<>(result);
        List<CreativeDTO> collectionList = new ArrayList<>(result);

        timeList.sort(Comparator.comparing(CreativeDTO::getCreateTime).reversed());;//按创建时间排序
        hashMap.put("time",timeList);

        viewList.sort((t1,t2)->t2.getView().compareTo(t1.getView()));
        hashMap.put("view",viewList);

        collectionList.sort((t1,t2)->t2.getCollections().compareTo(t1.getCollections()));
        hashMap.put("collection",collectionList);

        return hashMap;
    }

    @Override   //新增创意
    public Creative insertCreative(Creative creative) {
        if (creative.getStatement().equals("已发布") || creative.getStatement().equals("回收"))
            throw new ServiceException(Constants.CODE_600,"创意状态不符合");
        try {
            creativeMapper.insert(creative);
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return creative;
    }


    @Override   //获取用户的已发布创意列表(时间排序)
    public List<Creative> getByUser(Integer userId) {
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("statement","已发布");
        List<Creative> result = creativeMapper.selectList(queryWrapper);
        result.sort(Comparator.comparing(Creative::getCreateTime).reversed());
        return result;
    }

    @Override   //创意社区搜索
    public HashMap<String,List<CreativeDTO>> getBySearch(String keyWord) {
        if (StrUtil.isBlank(keyWord)){
            return findAll();
        }
        else {
            HashMap<String,List<CreativeDTO>> all = findAll();
            HashMap<String,List<CreativeDTO>> hashMap = new HashMap<>();
            List<CreativeDTO> time = new ArrayList<>();
            List<CreativeDTO> collection = new ArrayList<>();
            List<CreativeDTO> view = new ArrayList<>();
            Pattern pattern = Pattern.compile(keyWord);
            for (CreativeDTO creativeDTO : all.get("time")) {
                Matcher matcher1 = pattern.matcher(creativeDTO.getName());
                Matcher matcher2 = pattern.matcher(creativeDTO.getUserDTO().getNickname());
                if (matcher1.find() || matcher2.find()) {
                    time.add(creativeDTO);
                }
            }
            hashMap.put("time",time);
            for (CreativeDTO creativeDTO : all.get("collection")) {
                Matcher matcher1 = pattern.matcher(creativeDTO.getName());
                Matcher matcher2 = pattern.matcher(creativeDTO.getUserDTO().getNickname());
                if (matcher1.find() || matcher2.find()) {
                    collection.add(creativeDTO);
                }
            }
            hashMap.put("collection",collection);
            for (CreativeDTO creativeDTO : all.get("view")) {
                Matcher matcher1 = pattern.matcher(creativeDTO.getName());
                Matcher matcher2 = pattern.matcher(creativeDTO.getUserDTO().getNickname());
                if (matcher1.find() || matcher2.find()) {
                    view.add(creativeDTO);
                }
            }
            hashMap.put("view",view);
            return hashMap;
        }
    }

    @Override   //查找发布创意的用户数
    public int getUserCount() {
        List<CreativeDTO> creativeDTOS = findAll().get("time");
        HashSet<Integer> hashSet = new HashSet<>();
        for (CreativeDTO creativeDTO : creativeDTOS) {
            hashSet.add(creativeDTO.getUserDTO().getId());
        }
        return hashSet.size();
    }

    @Override   //创意详情
    public CreativeDTO getDetails(Integer id) {
        if (id == null)
            throw new ServiceException(Constants.CODE_500,"系统错误");
        Creative creative;
        try {
            creative = creativeService.getById(id);
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (creative == null)
            throw new ServiceException(Constants.CODE_600,"未找到创意");
        User user = userMapper.selectById(creative.getUserId());
        CreativeDTO creativeDTO = new CreativeDTO();
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setNickname(user.getNickname());
        userDTO.setProfilepic(user.getProfilepic());

        creativeDTO.setMine(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId().equals(user.getId()));
        creativeDTO.setUserDTO(userDTO);
        creativeDTO.setEmail(user.getEmail());
        creativeDTO.setId(id);
        creativeDTO.setName(creative.getName());
        creativeDTO.setDetail(creative.getDetail());
        creativeDTO.setCreateTime(creative.getCreateTime().toLocalDate());
        creativeDTO.setRelativeTime(TimeUtil.createRelative(creative.getCreateTime()));
        creativeDTO.setType(creative.getType());
        creativeDTO.setView(creative.getView());
        creativeDTO.setFeature(Arrays.asList(creative.getFeature().split(" ")));
        creativeDTO.setCollections(collectionService.getCount(id));
        return creativeDTO;
    }


    @Override   //更新访问量
    public int updateView(Integer id) {
        Creative creative = creativeService.getById(id);
        creative.setView(creative.getView() + 1);
        creativeService.saveOrUpdate(creative);
        return creative.getView();
    }

    @Override   //更新创意
    public Result updateCreative(Creative creative) {
        Creative one = getOneById(creative.getId());
        if (one == null)
            throw new ServiceException(Constants.CODE_600,"未找到创意");
        //用户保存草稿
        if (creative.getStatement().equals("未发布")) {
            if (one.getStatement().equals("回收") || one.getStatement().equals("待审核") || one.getStatement().equals("已发布"))
                return Result.error(Constants.CODE_600,"创意状态不符合");
        }
        //用户发布方案
        else if (creative.getStatement().equals("待审核")) {
            if (one.getStatement().equals("回收"))
                return Result.error(Constants.CODE_600,"创意状态不符合");
            else if (one.getStatement().equals("已发布")) {
                creative.setView(0);
                if (creativeService.saveOrUpdate(creative)) {
                    commentService.removeByCreative(creative.getId());
                    return Result.success("修改成功");
                } else
                    return Result.error(Constants.CODE_500, "修改失败");
            }
        }
        if (creativeService.saveOrUpdate(creative))
            return Result.success();
        return Result.error(Constants.CODE_600,"保存失败");
    }

    @Override   //根据用户id，查找已发布创意
    public List<CreativeHomeDTO> getCreativeHomes(Integer userId) {
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("statement","已发布");
        List<Creative> creativeList = creativeMapper.selectList(queryWrapper);
        List<CreativeHomeDTO> creativeHomeDTOS = new ArrayList<>();

        for (Creative creative : creativeList) {
            CreativeHomeDTO creativeHomeDTO = new CreativeHomeDTO();
            creativeHomeDTO.setId(creative.getId());
            creativeHomeDTO.setName(creative.getName());
            creativeHomeDTO.setFeature(Arrays.asList(creative.getFeature().split(" ")));
            if (creative.getDetail().length() <= 150)
                creativeHomeDTO.setDetail(creative.getDetail());
            else
                creativeHomeDTO.setDetail(creative.getDetail().substring(0,150) + "……");
            creativeHomeDTO.setView(creative.getView());
            creativeHomeDTO.setCollections(collectionService.getCount(creative.getId()));
            creativeHomeDTO.setComments(commentService.getCount(creative.getId()));
            creativeHomeDTO.setCreateTime(creative.getCreateTime().toLocalDate());
            creativeHomeDTO.setRelativeTime(TimeUtil.createRelative(creative.getCreateTime()));

            creativeHomeDTOS.add(creativeHomeDTO);
        }
        creativeHomeDTOS.sort(Comparator.comparing(CreativeHomeDTO::getCreateTime).reversed());
        return creativeHomeDTOS;
    }

    @Override   //回收创意
    public boolean removeCreativeInfo(Integer id) {
        Creative one = getOneById(id);
        if (one.getStatement().equals("回收")) {
            boolean result = creativeService.removeById(id);
            collectionService.removeByCreative(id);
            commentService.removeByCreative(id);
            return result;
        }
        else
            throw new ServiceException(Constants.CODE_600,"创意状态不符合");
    }

    @Override   //个人中心创意管理
    public List<Creative> getCenter(Integer userId) {
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Creative> result = creativeMapper.selectList(queryWrapper);
        for (Creative creative : result) {
            creative.setCollections(collectionService.getCount(creative.getId()));
            creative.setComments(commentService.getCount(creative.getId()));
        }
        result.sort(Comparator.comparing(Creative::getCreateTime).reversed());
        return result;
    }

    @Override   //管理员获取已发布创意
    public Result adminGetPublished(int PageNum, int PageSize, Integer userId, String name, String sortWay) {
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("statement","已发布");
        if (userId != null)
            queryWrapper.eq("user_id",userId);
        queryWrapper.like("name",name);
        List<Creative> creativeList = creativeService.list(queryWrapper);
        Page page = new Page();
        for (Creative creative : creativeList){
            if (!creative.getSketch().equals("{}"))
                creative.setSketch(new JSONObject(creative.getSketch()).get("response").toString());
            if (!creative.getPicture().equals("{}"))
                creative.setPicture(new JSONObject(creative.getPicture()).get("response").toString());
        }
        if (sortWay.equals("new"))
            creativeList.sort(Comparator.comparing(Creative::getCreateTime).reversed());
        else
            creativeList.sort(Comparator.comparing(Creative::getCreateTime));
        return Result.success(page.startPage(creativeList,PageNum,PageSize));
    }

    @Override   //管理员获取待审核创意
    public Result adminGetToExamine(int PageNum, int PageSize, Integer userId, String name) {
        QueryWrapper<Creative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("statement","待审核");
        if (userId != null)
            queryWrapper.eq("user_id",userId);
        queryWrapper.like("name",name);
        List<Creative> creativeList = creativeService.list(queryWrapper);
        for (Creative creative : creativeList){
            if (!creative.getSketch().equals("{}"))
                creative.setSketch(new JSONObject(creative.getSketch()).get("response").toString());
            if (!creative.getPicture().equals("{}"))
                creative.setPicture(new JSONObject(creative.getPicture()).get("response").toString());
        }
        Page page = new Page();
        return Result.success(page.startPage(creativeList,PageNum,PageSize));
    }

    @Override   //管理员通过审核创意
    public Result toPublish(Integer id) {
        Creative find = creativeService.getById(id);
        Creative creative = new Creative();
        creative.setId(id);
        if (find == null)
            return Result.error(Constants.CODE_500,"未找到该创意");
        if (!find.getStatement().equals("待审核"))
            return Result.error(Constants.CODE_500,"创意状态不为待审核");
        creative.setStatement("已发布");
        creative.setCreateTime(LocalDateTime.now());
        if (creativeService.saveOrUpdate(creative))
            return Result.success("发布成功");
        else
            return Result.error(Constants.CODE_500,"发布失败");
    }

    @Override   //打回创意
    public Result toUnPublish(Integer id) {
        Creative find = creativeService.getById(id);
        Creative creative = new Creative();
        creative.setId(id);
        if (find == null)
            return Result.error(Constants.CODE_500,"未找到该创意");
        if (!find.getStatement().equals("已发布") && !find.getStatement().equals("待审核"))
            return Result.error(Constants.CODE_500,"创意状态不为已发布和待审核");
        else {
            if (find.getStatement().equals("已发布")) {
                creative.setStatement("未发布");
                creative.setView(0);
                if (creativeService.saveOrUpdate(creative)) {
                    commentService.removeByCreative(id);
                    return Result.success("修改成功");
                }
                else
                    return Result.error(Constants.CODE_500,"修改失败");
            }
            else {
                creative.setStatement("未发布");
                if (creativeService.saveOrUpdate(creative)) {
                    return Result.success("修改成功");
                }
                else
                    return Result.error(Constants.CODE_500,"修改失败");
            }
        }
    }

    @Override   //用户管理创意仓库
    public Result manageCreative(Creative creative) {
        Creative one = getOneById(creative.getId());
        if (one == null || !one.getUserId().equals(creative.getUserId()))
            return Result.error(Constants.CODE_600,"创意不存在");
        switch (creative.getStatement()) {
            //创意设为私密
            case "未发布":
                if (one.getStatement().equals("回收") || one.getStatement().equals("未发布"))
                    return Result.error(Constants.CODE_600, "创意状态不符合");
                else if (one.getStatement().equals("已发布")) {
                    creative.setView(0);
                    if (creativeService.saveOrUpdate(creative)) {
                        commentService.removeByCreative(creative.getId());
                        return Result.success("修改成功");
                    } else
                        return Result.error(Constants.CODE_500, "修改失败");
                }
                break;
            //用户发布创意
            case "待审核":
                if (one.getStatement().equals("回收") || one.getStatement().equals("待审核") || one.getStatement().equals("已发布"))
                    return Result.error(Constants.CODE_600, "创意状态不符合");
                break;
            //用户将创意加入回收站
            case "回收":
                if (one.getStatement().equals("回收"))
                    return Result.error(Constants.CODE_600, "创意状态不符合");
                else if (one.getStatement().equals("已发布")) {
                    creative.setView(0);
                    if (creativeService.saveOrUpdate(creative)) {
                        commentService.removeByCreative(creative.getId());
                        return Result.success("修改成功");
                    } else
                        return Result.error(Constants.CODE_500, "修改失败");
                }
                break;
        }
        if (saveOrUpdate(creative))
            return Result.success("操作成功");
        return Result.error(Constants.CODE_500,"修改失败");
    }

    @Override   //用户从回收站恢复创意
    public Result recoveryCreative(Creative creative) {
        Creative one = getOneById(creative.getId());
        if (one == null || !one.getUserId().equals(creative.getUserId()))
            return Result.error(Constants.CODE_600,"创意不存在");
        if (creative.getStatement().equals("未发布") && one.getStatement().equals("回收")) {
            if (saveOrUpdate(creative))
                return Result.success("恢复成功");
        }
        return Result.error(Constants.CODE_600,"创意状态不符合");
    }

    private Creative getOneById(Integer id) {
        Creative one;
        try {
            one = creativeService.getById(id);
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
}
